package topupways

import (
	"crypto/rand"
	"gpt-api/framework/codes"
	"gpt-api/framework/ginplus"
	"gpt-api/pkg/model"
	"gpt-api/pkg/response"
	"math/big"

	"github.com/gin-gonic/gin"
)

// 申请提现
func (h *Handler) ApplyTransfer(c *gin.Context) error {
	// 验证参数
	userId := ginplus.GetUserID(c)
	var req struct {
		CashAccountId uint `json:"cash_account_id" binding:"required,gte=0"` // 提现账号ID
		Amount        uint `json:"amount" binding:"required,gte=0"`          // 提现金额(单位：分)
	}
	if err := c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}

	// 最小申请金额
	if req.Amount < 5000 {
		return ginplus.ReplyError(c, codes.ApplyTransferMinAmount, nil)
	}

	// 查询用户信息验证余额
	user, err := (&model.Users{}).GetUserInfoById(h.db, uint64(userId))
	if err != nil {
		return ginplus.ReplyInternalError(c, err)
	}
	if int64(user.Balance*100) < int64(req.Amount) {
		return ginplus.ReplyError(c, codes.UserBalanceNotEnough, nil)
	}

	// 验证提现账号
	cashAccount, err := (&model.CashAccount{}).GetById(h.db, uint64(req.CashAccountId))
	if err != nil {
		return ginplus.ReplyInternalError(c, err)
	}
	if cashAccount.UserID != userId {
		return ginplus.ReplyError(c, codes.CashAccountNotFound, nil)
	}

	// 生成提现单号,随机数
	random, err := rand.Int(rand.Reader, big.NewInt(1000000000000000000))
	if err != nil {
		return ginplus.ReplyInternalError(c, err)
	}

	// 创建提现记录
	transfer := &model.Transfer{
		UserID:  uint64(userId),
		Code:    "I" + random.String(),
		Amount:  uint64(req.Amount),
		Type:    uint8(cashAccount.Type),
		Account: cashAccount.Account,
		Name:    cashAccount.Name,
		Phone:   cashAccount.Phone,
		Idcard:  cashAccount.Idcard,
		Status:  1,
	}
	if _, err := transfer.Create(h.db); err != nil {
		return ginplus.ReplyInternalError(c, err)
	}

	return ginplus.ReplyJSON(c, nil)
}

// 提现列表
func (h *Handler) ListTransfer(c *gin.Context) error {
	userId := ginplus.GetUserID(c)
	// 验证参数
	var req struct {
		Page int `form:"page" default:"1"`
		Size int `form:"size" default:"10"`
	}
	if err := c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}

	// 获取提现列表
	list, err := (&model.Transfer{}).GetTransferByUserId(h.db, uint64(userId), req.Page, req.Size)
	if err != nil {
		return ginplus.ReplyInternalError(c, err)
	}

	// 整理返回数据
	resp := make([]response.TransferListResp, 0, len(list))
	for _, v := range list {
		resp = append(resp, response.TransferListResp{
			Id:       v.ID,
			Amount:   v.Amount,
			Status:   v.Status,
			Code:     v.Code,
			CreateAt: v.CreatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	return ginplus.ReplyJSON(c, resp)
}
